package com.haoma.controller;


import com.haoma.minio.dto.TaskInfoDto;
import com.haoma.minio.entity.UploadTask;
import com.haoma.minio.vo.InitTaskParam;
import com.haoma.result.Result;
import com.haoma.service.SysUploadTaskService;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;


/**
 * 分片上传-分片任务记录(SysUploadTask)表控制层
 *
 * @since 2022-08-22 17:47:31
 */
@RestController
@RequestMapping("/admin/minio/tasks")
public class MinioUploadTaskController {
    /**
     * 服务对象
     */
    @Resource
    private SysUploadTaskService sysUploadTaskService;


    /**
     * 获取上传进度
     *
     * @param identifier 文件md5
     * @return
     */
    @GetMapping("/{identifier}")
    public Result<TaskInfoDto> taskInfo(@PathVariable("identifier") String identifier) {
        TaskInfoDto taskInfo = sysUploadTaskService.getTaskInfo(identifier);
        return Result.success(taskInfo);
    }

    /**
     * 创建一个上传任务
     *
     * @return
     */
    @PostMapping("/post")
    public Result<TaskInfoDto> initTask(@Valid @RequestBody InitTaskParam param, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return Result.error(bindingResult.getFieldError().getDefaultMessage());
        }
        TaskInfoDto taskInfoDto = sysUploadTaskService.initTask(param);
        return Result.success(taskInfoDto);
    }

    /**
     * 获取每个分片的预签名上传地址
     *
     * @param identifier
     * @param partNumber
     * @return
     */
    @GetMapping("/{identifier}/{partNumber}")
    public Result preSignUploadUrl(@PathVariable("identifier") String identifier, @PathVariable("partNumber") Integer partNumber) {
        UploadTask task = sysUploadTaskService.getByIdentifier(identifier);
        if (task == null) {
            return Result.error("分片任务不存在");
        }
        Map<String, String> params = new HashMap<>();
        params.put("partNumber", partNumber.toString());
        params.put("uploadId", task.getUploadId());
        String s = sysUploadTaskService.genPreSignUploadUrl(task.getBucketName(), task.getObjectKey(), params);
        return Result.success(s);
    }

    /**
     * 合并分片
     *
     * @param identifier
     * @return
     */
    @PostMapping("/merge/{identifier}")
    public Result merge(@PathVariable("identifier") String identifier) {
        sysUploadTaskService.merge(identifier);
        return Result.success();
    }

}
